package com.sparkseries.redis;

import com.alibaba.nacos.common.utils.ThreadFactoryBuilder;
import com.sparkseries.common.util.redis.RedisKeys;
import com.sparkseries.common.util.redis.RedisUtils;
import com.sparkseries.domain.MyNotice;
import com.sparkseries.domain.SysNotice;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
@Slf4j
public class Producer {

    @Resource
    private RedisUtils redisUtils;

    // 线程池核心线程数
    private static final int CORE_POOL_SIZE = 5;
    // 线程池最大线程数
    private static final int MAX_POOL_SIZE = 200;
    // 线程空闲时间
    private static final long KEEP_ALIVE_TIME = 0L;
    // 时间单位
    private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
    // 任务队列容量
    private static final int QUEUE_CAPACITY = 1024;

    private final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .nameFormat("notice-producer")
            .build();

    private final ExecutorService pool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TIME_UNIT,
            new LinkedBlockingQueue<>(QUEUE_CAPACITY),
            namedThreadFactory,
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    @Async
    public Future<Long> createNotice(SysNotice sysNotice) {
        try {
            return pool.submit(() -> redisUtils.leftPush(RedisKeys.getSysNoticeKey(), sysNotice));
        } catch (Exception e) {
            log.error("创建通知时发生异常: ", e);
            return new FutureTask<>(() -> null); // 返回一个空的 Future 以保持方法签名一致
        }
    }

    @Async
    public Future<Long> saveMyNotice(MyNotice myNotice) {
        try {
            return pool.submit(() -> redisUtils.leftPush(RedisKeys.getMyNoticeKey(), myNotice));
        } catch (Exception e) {
            log.error("创建消息时发生异常: ", e);
            return new FutureTask<>(() -> null);
        }
    }
}
